package com.sgb.kjwl.view.widget.lease.common;

import android.content.Context;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;


import androidx.databinding.DataBindingUtil;


import com.sdk.mobile.manager.login.NoDoubleClickListener;
import com.sgb.kjwl.R;

import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.databinding.ViewLeaseReleaseBinding;
import com.sgb.kjwl.model.entity.request.LeaseDemandEntity;
import com.sgb.kjwl.view.widget.SimpleCountDownTimer2;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;


import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * 租赁发布需求公用界面
 */
public class LeaseReleaseView extends RelativeLayout {

    private Context mContext;
    private ViewLeaseReleaseBinding binding;
    private LeaseDemandEntity entity = new LeaseDemandEntity();
    private SimpleCountDownTimer2 mCountDownTimerUtils;

    public LeaseReleaseView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        initView();
    }

    private void initView() {
        binding = DataBindingUtil.inflate(LayoutInflater.from(mContext), R.layout.view_lease_release, this, true);
        initListener();
        initPhoneAndCode();
    }

    private void initListener() {
        binding.ivMap.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View view) {
                if (listener != null) {
                    listener.onMap();
                }
            }
        });
        binding.etAddress.setOnClickListener(v -> binding.ivMap.callOnClick());

        binding.tvCodeGet.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View view) {
                codeValidation();
            }
        });

        binding.tvSubmit.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View view) {
                if (verifyData()) {
                    entity.setTitle(binding.etTitle.getText().toString().trim());
                    entity.setContactName(binding.etContact.getText().toString().trim());
                    entity.setContactPhone(binding.etPhone.getText().toString().trim());
                    entity.setVerificationCode(binding.etCode.getText().toString().trim());
                    onPublishDemand(entity);
//                    showDialog(entity);
                }
            }
        });
        binding.etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().trim().length() == 11 && binding.llCode.getVisibility() == View.GONE) {
                    if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                        binding.llCode.setVisibility(VISIBLE);
                        binding.tvRegisterTip.setVisibility(VISIBLE);
                    }
                }
            }
        });
    }

    public void initPhoneAndCode() {
        if (!TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
            binding.etPhone.setText(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_PHONE, ""));
            binding.etPhone.setClickable(false);
        } else {
            binding.etPhone.setText("");
            binding.etPhone.setClickable(true);
        }
        binding.llCode.setVisibility(GONE);
        binding.tvRegisterTip.setVisibility(GONE);

    }

    public void setAddressText(String addressText, double latitude, double Longitude) {
        entity.setLatitude(latitude);
        entity.setLongitude(Longitude);
        entity.setAddress(addressText);
        binding.etAddress.setText(addressText);
    }

    private boolean verifyData() {
        if (TextUtils.isEmpty(binding.etTitle.getText())) {
            MToast.showToast(mContext, "请输入我的需求");
            return false;
        } else if (TextUtils.isEmpty(binding.etAddress.getText())) {
            MToast.showToast(mContext, "请选择工作地");
            return false;
//        } else if (TextUtils.isEmpty(binding.etContact.getText())) {
//            MToast.showToast(mContext, "请填联系人");
//            return false;
        } else if (TextUtils.isEmpty(binding.etPhone.getText())) {
            MToast.showToast(mContext, "请输入手机号");
            return false;
        } else if (!CheckUtils.isMobileNum(binding.etPhone.getText().toString())) {
            MToast.showToast(mContext, "格式错误，请重新输入联系电话");
            return false;
        } else if (binding.llCode.getVisibility() == VISIBLE && TextUtils.isEmpty(binding.etCode.getText())) {
            MToast.showToast(mContext, "请输入验证码");
            return false;
        }
        return true;
    }

    private void codeValidation() {
        if (TextUtils.isEmpty(binding.etPhone.getText())) {
            MToast.showToast(mContext, "请输入手机号");
            return;
        } else if (!CheckUtils.isMobileNum(binding.etPhone.getText().toString())) {
            MToast.showToast(mContext, "格式错误，请重新输入联系电话");
            return;
        }

        mCountDownTimerUtils = new SimpleCountDownTimer2(mContext, binding.tvCodeGet, 60000, 1000); // 倒计时1分钟
        mCountDownTimerUtils.start();
        //调用获取验证码接口
        getCodeModel(binding.etPhone.getText().toString().trim());
    }

    private void clearText() {
        binding.etTitle.setText("");
        binding.etAddress.setText("");
        binding.etContact.setText("");
        binding.etCode.setText("");
        if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
            binding.etPhone.setText("");
        }
        if(mCountDownTimerUtils!=null){
            mCountDownTimerUtils.onReset();
        }
    }

    //快捷需求-发布
    public void onPublishDemand(LeaseDemandEntity entity) {
        DialogHelper.showProgressDialog(mContext, "发布中");
        APIManager.getInstance().getLeaseAPI().publishDemand(entity)
                .enqueue(new Callback<BaseEntity>() {
                    @Override
                    public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                        DialogHelper.dismissProgressDialog();
                        if (response.body() == null) return;
                        if (response.body().getState().equals("ok")) {
                            MToast.showToast(mContext, "需求发布成功");
                            clearText();
                        } else {
                            MToast.showToast(mContext, response.body().getMsg() + "");
                        }
                    }

                    @Override
                    public void onFailure(Call<BaseEntity> call, Throwable t) {
                        DialogHelper.dismissProgressDialog();
                        MToast.showToast(mContext, "发布失败,服务器链接异常");
                    }
                });
    }

    //获取验证码
    public void getCodeModel(String phone) {
        APIManager.getInstance().getUserAPI().getRegisterCodeLease(phone).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                if (response.body() != null)
                    MToast.showToast(mContext, "验证码已发送");
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                MToast.showToast(mContext, t.getMessage());
            }
        });
    }

//    private void showDialog(LeaseDemandEntity entity) {
//        new CommonDialog(mContext).builder().setPositiveButton("确定").setNegativeButton("取消")
//                .setTitle("温馨提示")
//                .setMsg("确定要提交此需求吗？")
//                .setDialogCallBack(new CommonDialog.DialogCallBack() {
//                    @Override
//                    public void onRightClick() {
//                        onPublishDemand(entity);
//                    }
//
//                    @Override
//                    public void onLeftClick() {
//
//                    }
//                }).show();
//    }

    public interface OnCallBlackListener {
        void onMap();
    }

    private OnCallBlackListener listener;

    public void setOnCallBlackListener(OnCallBlackListener listener) {
        this.listener = listener;
    }

}
